'use strict';

const Controller = require('egg').Controller;

class ResumeController extends Controller {
  /**
   * 创建简历
   * POST /api/resumes
   */
  async create() {
    const { ctx } = this;

    try {
      const data = ctx.request.body;

      // 打印接收的数据（调试用）
      console.log('\n========== 收到创建简历请求 ==========');
      console.log('请求数据:', JSON.stringify(data, null, 2));
      console.log('======================================\n');

      // 验证必填字段
      if (!data.template_id) {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          msg: '模板ID不能为空',
          data: null
        };
        return;
      }

      if (!data.basic_info || !data.basic_info.name) {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          msg: '姓名不能为空',
          data: null
        };
        return;
      }

<<<<<<< HEAD
=======
      // 从JWT token中获取用户ID
      const userId = ctx.user?.id;
      if (!userId) {
        ctx.status = 401;
        ctx.body = {
          code: 401,
          msg: '未登录',
          data: null
        };
        return;
      }

      // 设置用户ID
      data.user_id = userId;

>>>>>>> resume
      // 创建简历
      const resume = await ctx.service.resume.createResume(data);

      console.log('✅ 简历创建成功！ID:', resume.id);

      ctx.status = 201;
      ctx.body = {
        code: 0,
        msg: '简历创建成功',
        data: resume
      };
    } catch (error) {
      console.error('\n========== ❌ 创建失败 ==========');
      console.error('错误:', error.message);
      console.error('堆栈:', error.stack);
      console.error('==================================\n');

      ctx.status = 500;
      ctx.body = {
        code: -1,
        msg: '创建简历失败：' + error.message,
        data: null
      };
    }
  }

  /**
   * 获取简历列表
   * GET /api/resumes
   */
  async index() {
    const { ctx } = this;

    try {
<<<<<<< HEAD
      const query = ctx.query;
      const result = await ctx.service.resume.getResumeList(query);

      ctx.body = {
        code: 0,
        msg: '获取简历列表成功',
        data: result
=======
      // 从JWT token中获取用户ID（可选，管理员可以不登录）
      const userId = ctx.user?.id;
      
      // 普通用户只能查看自己的简历，管理员可以查看所有
      const query = { ...ctx.query };
      if (userId && ctx.user.role !== 'admin') {
        // 普通用户强制设置为自己的ID
        query.user_id = userId;
      }
      
      const result = await ctx.service.resume.getResumeList(query);

      ctx.body = {
        code: 200,
        message: '获取简历列表成功',
        data: result.list || [],
        pagination: {
          current: result.page || parseInt(query.page || 1),
          pageSize: result.pageSize || parseInt(query.pageSize || 10),
          total: result.total || 0,
          pages: Math.ceil((result.total || 0) / parseInt(query.pageSize || 10))
        }
>>>>>>> resume
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
<<<<<<< HEAD
        code: -1,
        msg: error.message,
=======
        code: 500,
        message: error.message,
>>>>>>> resume
        data: null
      };
    }
  }

  /**
   * 获取简历详情
   * GET /api/resumes/:id
   */
  async show() {
    const { ctx } = this;

    try {
      const id = ctx.params.id;
      const resume = await ctx.service.resume.getResumeById(id);

      ctx.body = {
        code: 0,
        msg: '获取简历详情成功',
        data: resume
      };
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        code: error.status || -1,
        msg: error.message,
        data: null
      };
    }
  }

  /**
   * 更新简历
   * PUT /api/resumes/:id
   */
  async update() {
    const { ctx } = this;

    try {
      const id = ctx.params.id;
      const data = ctx.request.body;

      const resume = await ctx.service.resume.updateResume(id, data);

      ctx.body = {
        code: 0,
        msg: '简历更新成功',
        data: resume
      };
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        code: error.status || -1,
        msg: error.message,
        data: null
      };
    }
  }

  /**
   * 删除简历
   * DELETE /api/resumes/:id
   */
  async destroy() {
    const { ctx } = this;

    try {
      const id = ctx.params.id;
      await ctx.service.resume.deleteResume(id);

      ctx.body = {
<<<<<<< HEAD
        code: 0,
        msg: '简历删除成功',
        data: null
      };
=======
        code: 200,
        message: '简历删除成功',
        data: null
      };
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        code: 500,
        message: error.message,
        data: null
      };
    }
  }

  /**
   * 分享简历
   * POST /api/resumes/:id/share
   */
  async share() {
    const { ctx } = this;

    try {
      const id = ctx.params.id;
      const resume = await ctx.service.resume.shareResume(id);

      ctx.body = {
        code: 0,
        msg: '简历分享成功',
        data: resume
      };
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        code: error.status || -1,
        msg: error.message,
        data: null
      };
    }
  }

  /**
   * 取消分享简历
   * POST /api/resumes/:id/unshare
   */
  async unshare() {
    const { ctx } = this;

    try {
      const id = ctx.params.id;
      const resume = await ctx.service.resume.unshareResume(id);

      ctx.body = {
        code: 0,
        msg: '取消分享成功',
        data: resume
      };
>>>>>>> resume
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        code: error.status || -1,
        msg: error.message,
        data: null
      };
    }
  }
<<<<<<< HEAD
=======

  /**
   * 获取分享的简历列表
   * GET /api/resumes/shared
   */
  async shared() {
    const { ctx } = this;

    try {
      const query = ctx.query;
      const result = await ctx.service.resume.getSharedResumeList(query);

      ctx.body = {
        code: 0,
        msg: '获取分享简历列表成功',
        data: result
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        code: -1,
        msg: error.message,
        data: null
      };
    }
  }
>>>>>>> resume
}

module.exports = ResumeController;

